package br.ita.magiu.html;

public class HtmlHelper {

	private static final char invalidChars[] = { '<', '>', '&', '\"'};
	
	private static final String expansion[] = {"&lt;", "&gt;", "&amp;", "&quot;"};
	 
	/**
	 * Replaces some special chars, such as '<', '>', '&', '\"', that are used by an HTML document by it's encoded equivalent
	 * @param s String to be encoded
	 * @return Encoded String
	 */
	public static String encode(String s) {
		StringBuffer sb = new StringBuffer();
    	if(s != null) {
	   	 	for (int i = 0; i < s.length(); i++) {
	   	 		boolean copy = true;
	   	 		char ch = s.charAt(i);
	   	 		for (int j = 0; j < invalidChars.length ; j++) {
	   	 			if (invalidChars[j]==ch) {
	   	 				sb.append(expansion[j]);
	   	 				copy = false;
	   	 				break;
	   	 			}
	   	 		}
	   	 		if (copy) sb.append(ch);
	   	 	}
    	}
    	return sb.toString();
	}
	 
	/**
	 * Valid IDs and Names are defined in http://www.w3.org/TR/html401/types.html#type-id
	 * @param c
	 * @return
	 */
	public static boolean isAllowableSpecialCharacter(char c) {
		switch(c) {
		case '-':
		case '_':
		case ':':		
			return true;
		default:
			return false;
		}
	}
	
	public static boolean isDigit(char c) {
		return ('0' <= c && c <= '9');
	}
	
	public static boolean isLetter(char c) {
		return (('A' <= c && c <='Z')||('a' <= c && c <= 'z'));
	}
	
	public static boolean isValidCharacter(char c) {
		return isAllowableSpecialCharacter(c) || isDigit(c) || isLetter(c);
	}
}